package inventory;

import factory.ItemFactory;
import item.EquipableItem;

import java.util.HashMap;

import loadsave.Memento;
import loadsave.loadsaveobject.Iterator;
import loadsave.loadsaveobject.LoadSaveMapComposite;
import loadsave.loadsaveobject.LoadSaveObject;
import loadsave.loadsaveobject.LoadSaveObjectComposite;
import loadsave.loadsaveobject.LoadSavePrimitive;
import model.ModelObject;

public class EquippedInventory extends ModelObject {

	private HashMap<EquipLocation,EquipableItem> itemList;
	
	public EquippedInventory() {
		super("equippped_inventory");
		itemList = new HashMap<EquipLocation,EquipableItem>();
	}
	
	public EquippedInventory(HashMap<EquipLocation,EquipableItem> list) {
		super("equipped_inventory");
		itemList = list;
	}
	
	public EquipableItem addItem(EquipLocation loc, EquipableItem item) {
		EquipableItem eItem = itemList.put(loc,item);
		this.notifyObservers();
		return eItem;
	}
	
	public EquipableItem removeItem(EquipLocation loc) {
		this.notifyObservers();
		return itemList.remove(loc);
	}
	
	public EquipableItem getItemAt(EquipLocation loc) {
		return (itemList.get(loc));
	}

    public Memento getMemento() {
    	return new Memento() {

			@Override
			public LoadSaveObject getState() {
				LoadSaveObjectComposite toReturn = new LoadSaveObjectComposite("", "EquippedInventory");
				LoadSaveObject lso = EquippedInventory.super.getMemento().getState();
				Iterator<LoadSaveObject> i = lso.getIterator();
				for (i.init(); i.hasNext(); i.next()) {
					toReturn.add(i.getCurrKey().getValue(), i.getCurrVal());
				}
				LoadSaveMapComposite lsmc = new LoadSaveMapComposite("itemList", "HashMap", "EquipLocation", "EquipableItem");
				for (EquipLocation p : itemList.keySet()) {
					lsmc.add(new LoadSavePrimitive("","", p.toString()), itemList.get(p).getMemento().getState());
				}
				toReturn.add(lsmc.getName(), lsmc);
				return toReturn;
			}

			@Override
			public void restoreState(LoadSaveObject lso) {
				EquippedInventory.super.getMemento().restoreState(lso);
				itemList = new HashMap<EquipLocation, EquipableItem>();
				Iterator<LoadSaveObject> i = lso.get("itemList").getIterator();
				for (i.init(); i.hasNext(); i.next()) {
					EquipLocation p = EquipLocation.valueOf(i.getCurrKey().getValue());
					itemList.put(p, (EquipableItem) ItemFactory.createItem(i.getCurrVal()));
				}
			}
    		
    	};
    }
}
